const Service = require("egg").Service;
const { list_to_tree, get_all_folder_id } = require("../utils/tools");

class NoteService extends Service {
  // 笔记详情
  async detail_by_id(id) {
    const result = await this.app.mysql.get("note", {
      id,
    });
    return result;
  }

  // 新增笔记
  async add({ title, content, type = "" }) {
    const menu = await this.app.mysql.get("note", {
      title,
    });
    const tem = {};
    if (menu) {
      tem.type = "fail";
      tem.message = "该笔记已经存在!";
    } else {
      const result = await this.app.mysql.insert("note", {
        title,
        content,
        type,
        create_time: Date.now(),
        update_time: Date.now(),
      });
      tem.type = "success";
      tem.message = "新增成功";
    }

    return tem;
  }

  // 修改笔记
  async edit({ id, title, content, type = "" }) {
    const result = await this.app.mysql.update("note", {
      id,
      title,
      content,
      type,
      update_time: Date.now(),
    });
    return result;
  }

  // 查询笔记
  async list(keyword = "", page = 1, page_size = 5) {
    const offset = (page - 1) * page_size;
    let query = "";
    const keyword_=`title like '%${keyword}%' or content like '%${keyword}%'`
    if (keyword) {
      query = `select * from note where ${keyword_} ORDER BY create_time DESC LIMIT ${page_size} OFFSET ${offset};`;
    } else {
      query = `SELECT * FROM note ORDER BY create_time DESC LIMIT ${page_size} OFFSET ${offset};`;
    }

    const data = await this.app.mysql.query(query);

    let total_query = "";

    if (keyword) {
      total_query = `SELECT * FROM note WHERE ${keyword_}`;
    } else {
      total_query = `SELECT * FROM note`;
    }
    // 查询总数
    const total_ = await this.app.mysql.query(total_query);
    return {
      data,
      total:total_.length,
    };
  }
  // 删除笔记
  async delete(ids) {
    const result = await this.app.mysql.query(
      `delete from note where id in (${ids});`
    );
    return result;
  }
}

module.exports = NoteService;
